package com.yangye.wechat.service.impl;

import com.yangye.wechat.constants.Constants;
import com.yangye.wechat.entities.message.Music;
import com.yangye.wechat.entities.repository.Cache;
import com.yangye.wechat.service.CoreService;
import com.yangye.wechat.utils.HttpClientUtil;
import com.yangye.wechat.utils.JsonMapper;
import com.yangye.wechat.utils.MessageResponseUtil;
import com.yangye.wechat.utils.MessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

@Service
@Slf4j
public class CoreServiceImpl implements CoreService {

	private static final JsonMapper jsonMapper = JsonMapper.JSON_NON_DEFAULT_MAPPER;

	@Override
	public String processRequest(HttpServletRequest request) {
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "请求处理异常，请稍候尝试！";
			// xml请求解析
			// 调用消息工具类MessageUtil解析微信发来的xml格式的消息，解析的结果放在HashMap里
			Map<String, String> requestMap = MessageUtil.parseXml(request);
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");

			switch (msgType) {
				case MessageUtil.REQ_MESSAGE_TYPE_TEXT:// 文本消息
					String requestContent = requestMap.get("Content");

					respMessage = handleTextRequest(fromUserName, toUserName, requestContent);
					break;
				case MessageUtil.REQ_MESSAGE_TYPE_EVENT:// 订阅事件
					if (MessageUtil.EVENT_TYPE_SUBSCRIBE.equals(requestMap.get("Event"))) {
						respMessage = MessageResponseUtil.createTextMessage(fromUserName, toUserName, Constants.SUBSCRIBE_MESSAGE);
					}
					break;
				default:
					break;
			}

			log.info("fromUserName is:" + fromUserName + " toUserName is:" + toUserName + " msgType is:" + msgType);
		} catch (Exception e) {
			log.error("failed to process request, cause:{}", e.getMessage());
		}
		return respMessage;
	}



	/**
	 * 调用图灵机器人api接口，获取智能回复内容
	 * @param content
	 * @return
	 */
	private String robotChat(String content) {
		/** 此处为图灵api接口，参数key需要自己去注册申请 */
		String apiUrl = "http://www.tuling123.com/openapi/api?key=" + Constants.TULING_API_KEY + "&info=";
		String param = "";
		try {
			param = apiUrl + URLEncoder.encode(content, "utf-8");
		} catch (UnsupportedEncodingException e1) {
			log.error("cannot encode url", e1.getMessage());
		} //将参数转为url编码

		/** 发送httpget请求 */
		HttpGet request = new HttpGet(param);
		String result = "";
		try {
			HttpResponse response = HttpClients.createDefault().execute(request);
			if(response.getStatusLine().getStatusCode()==200){
				result = EntityUtils.toString(response.getEntity());
			}
		} catch (Exception e) {
			log.error("cannot get result from tuling api", e.getMessage());
		}
		/** 请求失败处理 */
		if (null == result) {
			return "对不起，你说的话真是太高深了……";
		}

		try {
			JSONObject json = new JSONObject(result);
			//以code=100000为例，参考图灵机器人api文档
			if (100000 == json.getInt("code")) {
				result = json.getString("text");
			}
		} catch (JSONException e) {
			log.error("cannot parse json", e.getMessage());
		}
		return result;
	}

	private String handleTextRequest(String fromUserName, String toUserName, String requestContent) {
		String responseMessage = "";
		switch (requestContent) {
			case "?":
			case "？":
				responseMessage = MessageResponseUtil.createTextMessage(fromUserName, toUserName, Constants.MENU);
				break;
			case "1":
				responseMessage = MessageResponseUtil.createTextMessage
						(fromUserName, toUserName, "你特么说的不是废话");
				break;
			case "2":
				responseMessage = MessageResponseUtil.createTextMessage
						(fromUserName, toUserName, "真可怜，年纪轻轻眼就瞎了");
				break;
			case "3":
				responseMessage = MessageResponseUtil.createMusicMessage
						(fromUserName, toUserName, Cache.music);
				break;
			case "4":
				responseMessage = MessageResponseUtil.createTextMessage
						(fromUserName, toUserName, "都说没空开发了。。");
				break;
			default:
				if (requestContent.contains("野")) {
					responseMessage = MessageResponseUtil.createTextMessage
							(fromUserName, toUserName, "大野子是最帅的");
				} else {
					responseMessage = MessageResponseUtil.createTextMessage
							(fromUserName, toUserName, robotChat(requestContent));
				}
				break;
		}
		return responseMessage;
	}

	private static void setMusic(String keyword) {
		String resJson = HttpClientUtil.sendHttpGet("https://c.y.qq.com/soso/fcgi-bin/search_for_qq_cp?g_tk=5381&uin=0&format=json&inCharset=utf-8&outCharset=utf-8&notice=0&platform=h5&needNewCode=1&w=" + keyword + "&zhidaqu=1&catZhida=1&t=0&flag=1&ie=utf-8&sem=1&aggr=0&perpage=20&n=20&p=1&remoteplace=txt.mqq.all");
		Map map = jsonMapper.fromJson(resJson, Map.class);
		System.out.println(map.get("data"));
		System.out.println(resJson);
	}

	public static void main(String[] args) {
		//http://ws.stream.qqmusic.qq.com/C100{songmid}.m4a?fromtag=0&guid=126548448
		//http://y.gtimg.cn/music/photo_new/T002R150x150M000{albummid}.jpg?max_age=2592000
		//https://c.y.qq.com/soso/fcgi-bin/search_for_qq_cp?g_tk=5381&uin=0&format=json&inCharset=utf-8&outCharset=utf-8&notice=0&platform=h5&needNewCode=1&w={关键词}&zhidaqu=1&catZhida=1&t=0&flag=1&ie=utf-8&sem=1&aggr=0&perpage=20&n=20&p=1&remoteplace=txt.mqq.all
		setMusic("纸短情长");

	}
}
